import { useLoaderData, useNavigation } from "react-router-dom";
import { Card, Empty, Spin } from "antd";

import { getPosts } from "../utils/api";

export const loader = async () => {
  try {
    const posts = await getPosts();
    return { posts };
  } catch (error) {
    return null;
  }
};

const Posts = () => {
  const { posts } = useLoaderData();
  const navigation = useNavigation();

  if (!posts) return <Empty />;

  return navigation.state === "loading" ? (
    <Spin style={{ margin: "50%" }} size="large" />
  ) : (
    <ul>
      {posts.map((post) => (
        <Card style={{ marginTop: "20px" }} key={post.id} title={post.title}>
          {post.body}
        </Card>
      ))}
    </ul>
  );
};

export default Posts;
